<?php

namespace Modules\Edu\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Modules\Edu\Entities\Sign;
use Modules\Edu\Entities\SignTotal;
use Modules\Edu\Entities\User;
use Modules\Edu\Http\Requests\SignRequest;

class SignController extends Controller
{

    public function index()
    {
        $signs = Sign::site()->with('signTotal')->whereYear('created_at', now())->whereMonth('created_at', now())->whereDay('created_at', now())->get();

        return view('edu::sign.index', compact('signs'));
    }


    public function store(SignRequest $request, Sign $sign)
    {

        if (user()->make()->isSign) {
            return back()->with('danger', '今日已签到');
        }
        $sign['user_id'] = Auth::id();
        $sign['site_id'] = site()['id'];
        $sign->fill($request->input())->save();
        $this->updateTotal();
        return back()->with('success', '签到成功');
    }

    public function updateTotal()
    {
        $user = user()->make();

        SignTotal::updateOrCreate(['user_id' => user('id'), 'site_id' => site()['id']],
            ['month' => $user->monthSign, 'total' => $user->signTotal]);
    }

    public function destroy(Sign $sign)
    {
        $this->authorize('delete', $sign);
        $sign->delete();
        $this->updateTotal();
        return response()->json(['message', '删除成功']);
    }
}
